package com.ynjt.util;

import com.ynjt.model.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.Charset;

@ChannelHandler.Sharable
public class Encoder extends MessageToByteEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message msg, ByteBuf out) throws Exception {

        final byte[] idContent = msg.getId().getBytes();
        final byte[] nameContent  = msg.getName().getBytes("utf-8");
        final byte[] ipConent = msg.getIp().getBytes();
        final byte[] messageContent = msg.getContent().getBytes("utf-8");

        out.writeInt(idContent.length);
        out.writeInt(nameContent.length);
        out.writeInt(ipConent.length);
        out.writeInt(messageContent.length);

        out.writeBytes(idContent);
        out.writeBytes(nameContent);
        out.writeBytes(ipConent);
        out.writeBytes(messageContent);

    }
}
